﻿
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

namespace DotsGame
{
    [BurstCompile]
    partial struct jobs_battleunit : IJobEntity
    {
        public ThreadRandom trandom;
        public BattleCamp campA;
        public BattleCamp campB;
        public float delta;
        public EntityCommandBuffer.ParallelWriter commandBuffer;
        public NativeArray<dotsbuf_effect> config_effect;
        public void Execute([ChunkIndexInQuery] int chunk_index, [EntityIndexInQuery] int entity_index, Entity entity, ref LocalTransform tran, comp_BattleUnit unit)
        {
            if (unit.maintarget)
            {
                return;
            }
            var campTarget = unit.campid == 0 ? campB : campA;

            for (var i = 0; i < campTarget.mainTargets.Length; i++)
            {
                var t = campTarget.mainTargets[i];
                if (t.enable == false)
                    continue;
                {
                    var target = t.pos;
                    var dir = target - tran.Position;
                    var dist = math.length(dir);
                    if (dist > t.half)
                    {
                        var pos = tran.Position + math.normalize(dir) * unit.speed * delta;
                        tran.Position = pos;
                    }
                    else
                    {
                        //通过command 延迟销毁
                        commandBuffer.DestroyEntity(chunk_index, entity);
                        var eff = commandBuffer.Instantiate(chunk_index, config_effect[0].prefab);
                        var effcomp = new comp_autodestory_effect()
                        {
                            lifetime = config_effect[0].lifetime,
                        };
                        commandBuffer.AddComponent(chunk_index, eff, tran);
                        commandBuffer.AddComponent(chunk_index, eff, effcomp);

                    }
                    return;
                }
            }
        }
    }
}
